package www.wen.com.common.lib.data.entities

import kotlinx.coroutines.CoroutineScope

data class LazyEntity<out T>(val code: Int, val msg: String, val data: T)


suspend fun <T> LazyEntity<T>.executeResponse(
    successBlock: (suspend CoroutineScope.() -> Unit)? = null,
    errorBlock: (suspend CoroutineScope.() -> Unit)? = null
): Result<T> {
    return kotlinx.coroutines.coroutineScope {
        if (code == -1) {
            errorBlock?.let { it() }
            Result.Error(java.io.IOException(msg))
        } else {
            successBlock?.let { it() }
            Result.Success(data)
        }
    }
}

suspend fun <T : Any> LazyEntity<T>.doSuccess(successBlock: (suspend CoroutineScope.(T) -> Unit)? = null): LazyEntity<T> {
    return kotlinx.coroutines.coroutineScope {
        if (code == 0) successBlock?.invoke(this, this@doSuccess.data)
        this@doSuccess
    }
}

suspend fun <T : Any> LazyEntity<T>.doError(errorBlock: (suspend CoroutineScope.(String) -> Unit)? = null): LazyEntity<T> {
    return kotlinx.coroutines.coroutineScope {
        if (code == -1) errorBlock?.invoke(this, this@doError.msg)
        this@doError
    }
}
